<template>
  <div style="display: flex;height: 100%;">
    <div class="video-left">
      <p style="font-size: 20px">预留列表</p>
    </div>
    <div class="video-scroll-container">
      <div v-for="(video, index) in cameraData" :key="index" class="video-item" @click="showVideo(index)"
           v-show="index >= start && index <= end">
        <h2>{{ video.name }}</h2>
        <div v-show="!isError.includes(index)">
          <video :ref="'videoPlayer_' + index" class="video-js vjs-default-skin" width="100%" height="auto" controls

                 @error="() => handleVideoError(index)">
            <!-- 视频源 -->
            <source :src="video.url" type="application/x-mpegURL"> <!-- 将 type 设置为 application/x-mpegURL -->
            您的浏览器不支持 HTML5 视频。
          </video>
        </div>
          <!--          <div id="video-error-message" class="error-message" v-if="!videoIsAvailable">-->
          <!--            <p>视频加载中，可能已离线</p>-->
          <!--          </div>-->
<!--          <div v-show="isError.includes(index)">离线</div>-->
          <div v-show="isError.includes(index)">
<!--            <Button type="primary" @click="review(index)">-->
<!--              <Icon type="ios-arrow-back"></Icon>-->
<!--              刷新-->
<!--            </Button>-->
            <Card>
              <Icon type="ios-close-circle-outline" size="100" />
              <div slot="title">摄像头已离线</div>
            </Card>
          </div>
          <div>
            <Card>
              <!--          <div slot="title">视频信息</div>-->
              <div>
                <Row>
                  <i-col span="6">location:</i-col>
                  <i-col span="10">{{ video.location }}</i-col>
                </Row>
                <Row>
                  <i-col span="6">ip:</i-col>
                  <i-col span="10">{{ video.ip }}</i-col>
                </Row>
              </div>
            </Card>
            <!--        <div>-->
            <!--          <div style="margin-bottom: 5px;">location: <span style="color: blue;">{{ video.location }}</span></div>-->
            <!--          <div>ip: <span style="color: blue;">{{ video.ip }}</span></div>-->
            <!--        </div>-->

            <!--        <div>-->
            <!--          location: {{video.location}}<br/>-->
            <!--          ip: {{video.ip}}<br />-->
            <!--        </div>-->
          </div>
        </div>
      <div class="inner-div">
        <Button type="primary" @click="prevPage" :disabled="currentPage === 1">
          <Icon type="ios-arrow-back"></Icon>
          上一页
        </Button>
        <span style="width: 50px;"> {{ currentPage }} / {{ totalPage }} </span>
        <Button type="primary" @click="nextPage" :disabled="currentPage === totalPage">
          下一页
          <Icon type="ios-arrow-forward"></Icon>
        </Button>
        <!--        <button @click="prevPage" :disabled="currentPage === 1">上一页</button>-->
        <!--        <span>{{ currentPage }}</span>-->
        <!--        <button @click="nextPage" :disabled="currentPage === totalPage">下一页</button>-->
      </div>
      </div>

      </div>
</template>

<script>
import util from "../../api/util.js";
import videojs from 'video.js';
import 'video.js/dist/video-js.css';
import 'videojs-contrib-hls';

export default {
  mounted() {
    this.getCameraData(this.cameraPageSize, this.cameraCurrentPage);
  },
  data() {
    return {
      isError: [],
      videoIsAvailable: true,
      cameraData: [],
      cameraTotal: 0,
      cameraPageSize: 9,
      cameraCurrentPage: 1,
      selectedVideo: null,
      playerInitialized: false, // 标记播放器是否已初始化
      pageSize: 6, // 每页显示数量
      currentPage: 1 // 当前页码
    };
  },
  watch: {
    selectedVideo(newValue, oldValue) {
      // 当 selectedVideo 改变时，重新初始化播放器
      if (newValue !== null && this.playerInitialized) {
        this.$nextTick(() => {
          this.initializeVideoPlayer(newValue);
        });
      }
    }
  },
  computed: {
    totalPage() {
      return Math.ceil(this.cameraData.length / this.pageSize);
    },
    start() {
      return (this.currentPage - 1) * this.pageSize;
    },
    end() {
      return this.pageSize * this.currentPage - 1;
    },
    displayedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.cameraData.slice(start, end);
    }
  },
  methods: {
    review(index) {
      console.log(index);
      // const videoElement = this.videoRefs['videoPlayer_' + index];
      // videoElement.dispose();
      this.initializeVideoPlayer(index,true);
    },
    handleVideoError(index) {
      // this.videoIsAvailable = false;
      this.isError.push(index);
      console.log("视频出错" + "index" + index);
    },
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
      }
    },
    nextPage() {
      if (this.currentPage < this.totalPage) {
        this.currentPage++;
      }
    },
    showVideo(index) {
      this.selectedVideo = index;
    },
    hideVideo() {
      this.selectedVideo = null;
    },
    getCameraData(pageSize, currentPage) {
      let self = this;
      let param = {
        action: "getCameraData",
        pageSize: pageSize,
        currentPage: currentPage
      }

      util.post(self, "camera/getCameraData", param, function (res) {
        self.cameraData = res.data.data;
        self.cameraTotal = res.data.count;
        // 在获取数据后初始化视频播放器
        self.cameraData.forEach((video, index) => {
          self.$nextTick(() => {
            self.initializeVideoPlayer(index,false);
          });
        });
      })
    },
    // 初始化单个视频播放器
    initializeVideoPlayer(index,isReview) {
      try {
        let player;
        if (!isReview){
          player = videojs(this.$refs[`videoPlayer_${index}`][0], {
            fluid: true, // 使播放器响应式
            autoplay: false, // 自动播放
            controls: true, // 显示控制条
            preload: 'auto', // 自动加载
            controlBar: {
              persistentControls: true // 控制条持久显示
            },
            sources: [{
              src: this.cameraData[index].url,
              type: 'application/x-mpegURL' // 设置视频源类型为 HLS
            }]
          });
        }
        if (isReview) {
          // 获取要移除元素的索引位置
          var indexToRemove = this.isError.indexOf(index);
          // 如果要移除的元素在数组中存在
          if (indexToRemove !== -1) {
            // 使用splice()方法将其从数组中移除
            this.isError.splice(indexToRemove, 1);
          }
          console.log("aaaaaaaaaaaaa");
          // player.src(this.cameraData[index].url);
          player.dispose();
          player = videojs(this.$refs[`videoPlayer_${index}`][0], {
            fluid: true, // 使播放器响应式
            autoplay: false, // 自动播放
            controls: true, // 显示控制条
            preload: 'auto', // 自动加载
            controlBar: {
              persistentControls: true // 控制条持久显示
            },
            sources: [{
              src: this.cameraData[index].url,
              type: 'application/x-mpegURL' // 设置视频源类型为 HLS
            }]
          });

          player.play(); // 可选：重新加载后自动播放视频
        }
        // 监听播放事件
        player.on('play', () => {
          player.controlBar.show(); // 显示控制条
          player.controlBar.el().style.display = 'flex !important'; // 添加 !important
        });

        player.on('error', function () {
          console.log('视频加载失败');
          // this.videoIsAvailable = false;
          // 在页面上显示错误信息或者重新加载视频
          // 例如：显示错误提示信息
          // player.error({
          //   code: 4,
          //   message: '摄像头离线'
          // });

        });
        // player.on('loadeddata', function () {
        //   // 视频流加载完成，设置视频可用状态为 true
        //   this.videoIsAvailable = true;
        // });

        // player.on('error', function() {
        //   // 视频流加载失败或发生错误，设置视频可用状态为 false
        // });
        // player.error({
        //   code: 4,
        //   message: '摄像头离线'
        // });

        player.ready(function () {
          // 播放视频
          this.play();
        });
      } catch (e) {
        this.videoIsAvailable = false;
      }


    },

  },
};
</script>

<style scoped>
.video-scroll-container {
  position: relative; /* 外部div设置为相对定位 */
}

.inner-div {
  position: absolute; /* 内部div设置为绝对定位 */
  bottom: 20px; /* 相对于外部div底部偏移10px */
  right: 20px; /* 相对于外部div右侧偏移10px */
}

.video-left {
  flex-wrap: wrap;
  width: 20%;
  height: 95%;
  border-radius: 10px;
  /* 设置圆角 */
  padding: 10px;
  /* 可选：添加内边距以增加美观性 */
  margin: 10px;
  background-color: white;
  /* 设置背景颜色为白色 */
  box-shadow: 0px 8px 15px rgba(0, 0, 0, 0.1);
  /* 添加阴影效果 */
}

.video-scroll-container {
  display: flex;
  flex-wrap: wrap;
  width: 75%;
  height: 95%;
  gap: 10px;
  /* 视频之间的间隔 */
  overflow-y: auto;
  /* 垂直方向超出容器时显示滚动条 */
  max-height: 100%;
  /* 设置视频列表容器的最大高度 */
  background-color: white;
  /* 设置背景颜色为白色 */
  border-radius: 10px;
  /* 设置圆角 */
  padding: 10px;
  /* 可选：添加内边距以增加美观性 */
  margin: 10px;
  box-shadow: 0px 8px 15px rgba(0, 0, 0, 0.1);
  /* 添加阴影效果 */
}

.video-item {
  width: calc(33.33% - 20px);
  /* 每行显示三个视频，减去间隔 */
  padding: 10px;
  box-sizing: border-box;
  cursor: pointer;
}

.video-item h2 {
  margin-top: 0;
}

.fullscreen-video {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.fullscreen-video video {
  max-width: 90%;
  max-height: 90%;
}
</style>
